package com.rhino.xchat.http

import com.rhino.xchat.constant.Cache
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response

/**
 * 添加header
 *
 * @author LuoLin
 * @since Create on 2024/9/29.
 */
class HeaderInterceptor : Interceptor {

    companion object {
        fun createHeader(request: Request?): Map<String, String> {
            val headerMap: MutableMap<String, String> = HashMap()
            // TODO ll
            val token = Cache.getLoginInfo()?.getAccessToken() ?: ""
            if (token.isNotEmpty()) {
                headerMap["Authorization"] = "Bearer $token"
            }
            return headerMap
        }
    }

    override fun intercept(chain: Interceptor.Chain): Response {
        val request: Request = chain.request()
        val headers = createHeader(request)
        val newBuilder: Request.Builder = request.newBuilder()
        for ((key, value) in headers) {
            newBuilder.removeHeader(key)
            newBuilder.addHeader(key, value)
        }
        val newRequest: Request = newBuilder.build()
        return chain.proceed(newRequest)
    }
}